package org.hepeng.workx.spring.cloud.netflix.ribbon.loadbalancer;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.hepeng.workx.spring.cloud.netflix.ribbon.SafeRibbonCommandContext;
import org.springframework.util.MultiValueMap;

import java.util.Objects;

/**
 * @author he peng
 */
public class ServerPortRule extends AbstractRequestConditionalRule {

    private static final String PARAM_NAME = "port";

    @Override
    public Server choose(Object key, SafeRibbonCommandContext ribbonContext , ILoadBalancer lb) {
        MultiValueMap<String, String> params = ribbonContext.getParams();
        int paramPort = Integer.valueOf(params.getFirst(PARAM_NAME));

        for (Server server : lb.getAllServers()) {
            int serverPort = server.getPort();
            if (paramPort == serverPort) {
                return server;
            }
        }
        return null;
    }

    @Override
    protected boolean isSupported(Object key, SafeRibbonCommandContext ribbonContext) {
        MultiValueMap<String, String> params = ribbonContext.getParams();
        return Objects.isNull(params) || ! params.containsKey(PARAM_NAME);
    }
}
